@page
@model IndexModel
@{
    ViewData["Title"] = "实时流量监控";
}

<div class="row">
    <div class="col-md-12">
        <h1>实时流量监控</h1>
        <p class="text-muted">监控内网各设备的网络流量使用情况</p>

        <div class="card mb-4">
            <div class="card-header">
                <h5>系统概览</h5>
            </div>
            <div class="card-body">
                <div id="summaryStats" class="row">
                    <div class="col-md-3">
                        <div class="stat-card bg-primary text-white">
                            <h3 id="totalDevices">0</h3>
                            <p>总设备数</p>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="stat-card bg-success text-white">
                            <h3 id="activeDevices">0</h3>
                            <p>活跃设备</p>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="stat-card bg-info text-white">
                            <h3 id="totalDownload">0 MB</h3>
                            <p>总下载</p>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="stat-card bg-warning text-white">
                            <h3 id="totalUpload">0 MB</h3>
                            <p>总上传</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5>实时流量图表</h5>
                <div class="btn-group">
                    <button type="button" class="btn btn-sm btn-outline-secondary" onclick="setTimeRange('1h')">1小时
                    </button>
                    <button type="button" class="btn btn-sm btn-outline-secondary" onclick="setTimeRange('6h')">6小时
                    </button>
                    <button type="button" class="btn btn-sm btn-outline-secondary" onclick="setTimeRange('24h')">
                        24小时
                    </button>
                </div>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-12 mb-4">
                        <h6>下载速率</h6>
                        <div style="height: 300px;">
                            <canvas id="downloadChart"></canvas>
                        </div>
                    </div>
                    <div class="col-md-12">
                        <h6>上传速率</h6>
                        <div style="height: 300px;">
                            <canvas id="uploadChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row mt-4">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <h5>实时设备流量</h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-striped">
                        <thead>
                        <tr>
                            <th>设备名称</th>
                            <th>IP地址</th>
                            <th>MAC地址</th>
                            <th>下载速率</th>
                            <th>上传速率</th>
                            <th>总下载</th>
                            <th>总上传</th>
                            <th>最后更新</th>
                        </tr>
                        </thead>
                        <tbody id="trafficTableBody">
                        <!-- 实时数据将通过JavaScript填充 -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

@section Scripts {
    <script>
        // 全局变量
        let downloadChart = null;
        let uploadChart = null;
        let trafficData = {};
        let connection = null;
        let timeRange = '1h';

        // 初始化SignalR连接
        function initSignalR() {
            connection = new signalR.HubConnectionBuilder()
                .withUrl("/trafficHub")
                .build();

            connection.on("ReceiveTrafficUpdate", function (updates) {
                updateTrafficTable(updates);
                updateTrafficChart(updates); // 更新图表
                updateSummaryStats();
            });

            connection.on("ConnectionEstablished", function (connectionId) {
                console.log("SignalR连接已建立: " + connectionId);
                // 连接成功后立即获取一次数据
                fetchLatestData();
            });

            connection.start().then(function () {
                console.log("SignalR连接成功");
            }).catch(function (err) {
                console.error("SignalR连接失败: ", err);
                // 失败后10秒重试
                setTimeout(initSignalR, 10000);
            });

            // 监听连接关闭事件
            connection.onclose(function (error) {
                console.log("SignalR连接已关闭: ", error);
                // 连接关闭后10秒重试
                setTimeout(initSignalR, 10000);
            });
        }

        // 获取最新数据
        function fetchLatestData() {
            $.getJSON('/api/traffic/latest')
                .done(function (data) {
                    updateTrafficTable(data);

                })
                .fail(function () {
                    console.error("获取最新流量数据失败");
                });

            $.getJSON('/api/traffic/summary')
                .done(function (data) {
                    updateSummaryStats(data);
                })
                .fail(function () {
                    console.error("获取概览数据失败");
                });

            fetchTrafficHistory();
        }

        // 更新表格
        function updateTrafficTable(updates) {
            const tbody = $('#trafficTableBody');
            tbody.empty();

            updates.forEach(update => {
                // 转换流量单位
                const downloadRate = formatBytes(update.downloadSpeed) + "/s";
                const uploadRate = formatBytes(update.uploadSpeed) + "/s";
                const totalDownload = formatBytes(update.totalDownload);
                const totalUpload = formatBytes(update.totalUpload);
                const lastUpdated = new Date(update.timestamp).toLocaleTimeString();

                const row = `
                    <tr>
                        <td>${update.deviceName}</td>
                        <td>${update.ipAddress}</td>
                        <td>${update.macAddress}</td>
                        <td style="width:180px">${downloadRate}</td>
                        <td style="width:180px">${uploadRate}</td>
                        <td style="width:180px">${totalDownload}</td>
                        <td style="width:180px">${totalUpload}</td>
                        <td>${lastUpdated}</td>
                    </tr>
                `;
                tbody.append(row);
            });
        }

        // 更新概览统计
        function updateSummaryStats(data) {
            if (data) {
                $('#totalDevices').text(data.totalDevices);
                $('#activeDevices').text(data.activeDevices);
                $('#totalDownload').text(formatBytes(data.totalDownload));
                $('#totalUpload').text(formatBytes(data.totalUpload));
            }
        }

        // 获取流量历史数据
        function fetchTrafficHistory() {
            const now = new Date();
            let startDate = new Date();

            switch (timeRange) {
                case '1h':
                    startDate.setHours(now.getHours() - 1);
                    break;
                case '6h':
                    startDate.setHours(now.getHours() - 6);
                    break;
                case '24h':
                    startDate.setDate(now.getDate() - 1);
                    break;
            }

            $.getJSON(`/api/traffic/latest`)
                .done(function (updates) {
                    updateTrafficChart(updates);
                })
                .fail(function () {
                    console.error("获取设备列表失败");
                });
        }

        // 创建流量图表
        function createTrafficChart(updates) {
            const downloadCtx = document.getElementById('downloadChart').getContext('2d');
            const uploadCtx = document.getElementById('uploadChart').getContext('2d');

            // 如果已有图表，先销毁
            if (downloadChart) {
                downloadChart.destroy();
            }
            
            if (uploadChart) {
                uploadChart.destroy();
            }

            const labels = Array.from({length: 60}, (_, i) => {
                const date = new Date();
                date.setSeconds(date.getSeconds() - (59 - i) * 5);
                return date.toLocaleTimeString();
            });

            // 为下载图表创建数据集
            const downloadDatasets = [];
            updates.forEach(update => {
                const color = getRandomColor();
                downloadDatasets.push({
                    label: `${update.deviceName}`,
                    data: Array(60).fill(0),
                    borderColor: color,
                    backgroundColor: `${color}40`,
                    tension: 0.4
                });
            });

            // 为上传图表创建数据集
            const uploadDatasets = [];
            updates.forEach(update => {
                const color = getRandomColor();
                uploadDatasets.push({
                    label: `${update.deviceName}`,
                    data: Array(60).fill(0),
                    borderColor: color,
                    backgroundColor: `${color}40`,
                    tension: 0.4
                });
            });

            downloadChart = new Chart(downloadCtx, {
                type: 'line',
                data: {
                    labels: labels,
                    datasets: downloadDatasets
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                callback: function (value) {
                                    return formatBytes(value) + '/s';
                                }
                            }
                        }
                    },
                    plugins: {
                        tooltip: {
                            callbacks: {
                                label: function (context) {
                                    return context.dataset.label + ': ' + formatBytes(context.parsed.y) + '/s';
                                }
                            }
                        }
                    }
                }
            });
    
            uploadChart = new Chart(uploadCtx, {
                type: 'line',
                data: {
                    labels: labels,
                    datasets: uploadDatasets
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                callback: function (value) {
                                    return formatBytes(value) + '/s';
                                }
                            }
                        }
                    },
                    plugins: {
                        tooltip: {
                            callbacks: {
                                label: function (context) {
                                    return context.dataset.label + ': ' + formatBytes(context.parsed.y) + '/s';
                                }
                            }
                        }
                    }
                }
            });
        }

        // 更新流量图表数据
        function updateTrafficChart(updates) {
            if (!downloadChart || !uploadChart) {
                createTrafficChart(updates);
                return;
            }

            // 更新现有图表数据
            const now = new Date().toLocaleTimeString();
    
            // 更新下载图表
            downloadChart.data.labels.shift();
            downloadChart.data.labels.push(now);
    
            let datasetIndex = 0;
            updates.forEach(update => {
                if (datasetIndex < downloadChart.data.datasets.length) {
                    downloadChart.data.datasets[datasetIndex].data.shift();
                    downloadChart.data.datasets[datasetIndex].data.push(update.downloadSpeed);
                    datasetIndex++;
                }
            });
    
            downloadChart.update();
    
            // 更新上传图表
            uploadChart.data.labels.shift();
            uploadChart.data.labels.push(now);
    
            datasetIndex = 0;
            updates.forEach(update => {
                if (datasetIndex < uploadChart.data.datasets.length) {
                    uploadChart.data.datasets[datasetIndex].data.shift();
                    uploadChart.data.datasets[datasetIndex].data.push(update.uploadSpeed);
                    datasetIndex++;
                }
            });
    
            uploadChart.update();
        }

        // 设置时间范围
        function setTimeRange(range) {
            timeRange = range;
            fetchTrafficHistory();
        }

        // 格式化字节数
        function formatBytes(bytes) {
            if (bytes === 0) return '0 B';
            const k = 1024;
            const sizes = ['B', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        // 生成随机颜色
        function getRandomColor() {
            const letters = '0123456789ABCDEF';
            let color = '#';
            for (let i = 0; i < 6; i++) {
                color += letters[Math.floor(Math.random() * 16)];
            }
            return color;
        }

        // 变暗颜色
        function darkenColor(color, percent) {
            const num = parseInt(color.replace("#", ""), 16),
                amt = Math.round(2.55 * percent),
                R = (num >> 16) - amt,
                G = (num >> 8 & 0x00FF) - amt,
                B = (num & 0x0000FF) - amt;
            return "#" + (0x1000000 + (R < 255 ? R < 1 ? 0 : R : 255) * 0x10000 +
                (G < 255 ? G < 1 ? 0 : G : 255) * 0x100 +
                (B < 255 ? B < 1 ? 0 : B : 255)).toString(16).slice(1);
        }

        // 页面加载完成后初始化
        $(document).ready(function () {
            initSignalR();

            // 每30秒刷新一次数据（作为SignalR的备用方案）
            setInterval(fetchLatestData, 30000);
        });
    </script>
}